package gen.tools.deploy;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.as.cli.CommandContext;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.dmr.ModelNode;

public class IsFileExistInAP extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public IsFileExistInAP() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final String bssId = "fOrder";
		final String subsysId = request.getParameter("subsysId");
		final String envId = request.getParameter("envId");
		final String squadId = request.getParameter("squadId");
		final int depmainSN = Integer.parseInt( request.getParameter("depmainSN") );
		final String fileName = request.getParameter("fn");
		final String commandLine = ":read-resource()";
		
		CommandContext cmdCtx = null;
		ModelControllerClient client = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String res = "";
		
		try {
			final int fdepdetailid = wid.getfDepdetailid(depmainSN);	//取得細項ID
			conn = wid.getConn();

			String sql = "SELECT cip,cid,cport,cpwd FROM mpsquadenv WHERE bssId=? AND subsysId=? AND envId=? AND squadId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, bssId);
			ps.setString(2, subsysId);
			ps.setString(3, envId);
			ps.setString(4, squadId);
			rs = ps.executeQuery();
			rs.next();
			final String cip = rs.getString("cip");
			final String cid = rs.getString("cid");
			final int cport = rs.getInt("cport");
			final char[] cpwd = rs.getString("cpwd").toCharArray();
			String depResult = "true";
			try {
				cmdCtx = wid.initCommandContext(cip, cport, cid, cpwd);
				System.out.println("在"+squadId+"上連線成功");
				
				client = cmdCtx.getModelControllerClient();
				ModelNode requestNode = cmdCtx.buildRequest(commandLine);
				ModelNode result = client.execute(requestNode);
				String fileSets = result.get("result").get("deployment").toString();
				
				if ( fileSets.contains(fileName) ) {
					res = "存在";
				} else {
					res = "不存在";
				}
				System.out.println("檔案"+fileName+"在"+cip+" "+res);
				
				sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,hostIP,squadId,bDT,envId,depResult) VALUES(?,?,?,?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, depmainSN);
				ps.setInt(2, fdepdetailid);
				ps.setInt(3, 4);		// 4 檢查檔案是否存在Server Group
				ps.setString(4, cip);
				ps.setString(5, squadId);
				ps.setTimestamp(6, wid.cDT());
				ps.setString(7, envId);
				ps.setString(8, depResult);
				ps.execute();
				
				sql = "UPDATE fdepdetail SET eDT=?,depResult=? WHERE depmainSN=? AND fdepdetailid=?";
				ps = conn.prepareStatement(sql);
				ps.setTimestamp(1, wid.cDT() );
				ps.setString(2, depResult );
				ps.setInt(3, depmainSN);
				ps.setInt(4, fdepdetailid);
				ps.execute();
			} catch( Exception e ) {
				System.out.println("發生錯誤!!!");
				wid.errProcess(e);
				depResult = e.toString();
				sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,hostIP,squadId,bDT,envId,depResult) VALUES(?,?,?,?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, depmainSN);
				ps.setInt(2, fdepdetailid);
				ps.setInt(3, 4);		// 4 檢查檔案是否存在Server Group
				ps.setString(4, cip);
				ps.setString(5, squadId);
				ps.setTimestamp(6, wid.cDT());
				ps.setString(7, envId);
				ps.setString(8, depResult);
				ps.execute();
				throw e;
			}
		} catch( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
			if (client != null) { client.close(); }
			if (cmdCtx != null) {
				cmdCtx.disconnectController();
				cmdCtx.terminateSession();
			}
		}
		response.getWriter().write( res );
	}

}
